package com.wfcm.controller;

import java.io.*;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.wfcm.entity.*;
import com.wfcm.service.*;
import com.wfcm.utils.*;
import com.wfcm.wxUitls.Oauth2Token;
import com.wfcm.wxUitls.SNSUserInfo;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.wfcm.annotation.IgnoreSign;
import com.wfcm.annotation.IgnoreToken;
import redis.clients.jedis.JedisPool;

@Controller
@RequestMapping("/member")
@ResponseBody
public class MemberController {

	private static Logger log = LoggerFactory.getLogger(AdInfoController.class);
	/**
     * 允许图片
     */
    public static String[] UPLOAD_IMG_FILTER = {"GIF","PNG","JPG","JPEG"};
	 @Autowired
	 private WfPhoneCodeService phoneCodeService;
	 @Autowired
	 private WfMemberService memberService;
	 @Autowired
	 private WfMemberSessionService memberSessionService;
	 @Autowired
	 private WfMemberAddressService  memberAddressService;
	 @Autowired
	 private WfMemberChildrenService memberChildrenService;
	 @Autowired
	 private WfAreaService areaService;
	 @Autowired
	 private WfQuestionService questionService;
	 @Autowired
	 private WfOpinionService opinionService;
	 @Autowired
	 private WfMemberInvitationService memberInvitationService;
	 @Autowired
	 private WfMemberCouponsService memberCouponsService;
	 @Autowired
	 private WfCoinLogService coinLogService ;
	 @Autowired
	 private WfMemberGoldLogService memberGoldLogService ;
	 @Autowired
	 private WfMemberNewGoldLogService memberNewGoldLogService ;
	 @Autowired
	 private WfMemberGiveCoinLogService memberGiveCoinLogService ;
	 @Autowired
	 private WfMemberInvitationViewCoinService memberInvitationViewCoinService ;
	 @Autowired
	 private CourseInvitationService courseInvitationService;
	 @Autowired
	 private WfGoodsOrderService goodsOrderService;
	 @Autowired
	 private WfGoodsOrderRelationService goodsOrderRelationService;
	 @Autowired
	 private WfCourseChapterService courseChapterService;
	@Autowired
	private WfCommenmanagerService commenmanagerService ;
	@Autowired
	private WfMemberInvitationService invitationService;
	@Autowired
	private WfCourseWorkService courseWorkService;
	@Autowired
	private WfShoppingCartService shoppingCartService;
	@Autowired
	private WfCollageOrderService collageOrderService;

	 /**
	 * 注册登录
	 */
	@RequestMapping("/login")
	@IgnoreToken
	@ResponseBody
	public R login(String mobile, String code, Integer inviterId, Integer courseId, Integer courseType, Integer flag) {
		R result = new R();
		//判断验证码是否正确
 		Map<String,String> map =new  HashMap<>();
 		map.put("mobile", mobile);
 		map.put("code", code);
 		WfPhoneCodeEntity phoneCodeEntity =  phoneCodeService.queryPhoneCode(map);

 		if("606606".equals(code)) {
 			phoneCodeEntity =  new WfPhoneCodeEntity();
 		}

 		int couponFlag = 0;
 		if(phoneCodeEntity == null) {
 			return R.error(67,"验证码错误");
 		}else {
 			//删除验证码记录
 	 		phoneCodeService.deleteByPhone(phoneCodeEntity.getPhone());
 	 		//判断用户是否存在
 			WfMemberEntity  memberEntity = memberService.queryByMobile(mobile);

 			if(memberEntity == null) {

 				//若第一次登陆，则生成新用户
 				memberEntity = new WfMemberEntity();
 				memberEntity.setTelephone(mobile);
 				memberEntity.setStatus(1);//状态默认为启用
 				memberEntity.setCreatetime(new Date());
 				memberEntity.setUpdatetime(new Date());
 				String chineseName = getStringRandom(6);//随机名字
 				memberEntity.setUsername("姓名_"+chineseName);
 				String userPassword = DigestUtils.md5Hex("123456");
 				memberEntity.setUserpassword(userPassword);
 				memberEntity.setBlackflag(0);
 				memberService.save(memberEntity);

 				memberEntity = memberService.queryByMobile(mobile);

				/**
				 * 大礼包赠送课程（新用户）
				 */
				List<MemberGift> list = memberService.searchGift(mobile);
				if (list.size() > 0) {
					Integer userId = memberEntity.getUserid();
					String orderCode = DateUtil.getOrderNum();
					goodsOrderService.save(WfGoodsOrderEntity.generateFreeEntity(userId, orderCode));
					list.stream().forEach((item) -> {
						memberService.updateGift(item.getId());
						goodsOrderRelationService.save(WfGoodsOrderRelationEntity.generateFreeEntity
								(userId, orderCode, item.getCourseId(), item.getCourseType()));
					});
				}

 				if(null != inviterId) {
					/**
					 * 邀请新用户双方赠送课程
					 */
					if (null != courseId && null != courseType) {
						if (courseType.equals(2)) {
							WfCourseChapterEntity cc = courseChapterService.queryObjectById(courseId);
							courseId = cc.getCourseid();
							courseType = 1;
						}
						if (null != courseInvitationService.getCourseInvitation(new CourseInvitation(courseId, courseType))) {
							if (courseInvitationService.confirm(new CourseInvitation(inviterId, courseId, courseType))) {
								Integer inviteeId = memberEntity.getUserid();
								String inviterOrderCode = DateUtil.getOrderNum();
								String inviteeOrderCode = DateUtil.getOrderNum();
								if (goodsOrderRelationService.confirm(new WfGoodsOrderRelationEntity(inviterId, courseId, courseType))) {
									goodsOrderService.save(WfGoodsOrderEntity.generateFreeEntity(inviterId, inviterOrderCode));
									goodsOrderRelationService.save(WfGoodsOrderRelationEntity.generateFreeEntity
											(inviterId, inviterOrderCode, courseId, courseType));
								}
								if (goodsOrderRelationService.confirm(new WfGoodsOrderRelationEntity(inviteeId, courseId, courseType))) {
									goodsOrderService.save(WfGoodsOrderEntity.generateFreeEntity(inviteeId, inviteeOrderCode));
									goodsOrderRelationService.save(WfGoodsOrderRelationEntity.generateFreeEntity
											(inviteeId, inviteeOrderCode, courseId, courseType));
								}
								courseInvitationService.addCourseInvitationLog(new CourseInvitation(courseId, courseType,
										System.currentTimeMillis(), inviterOrderCode, inviteeOrderCode, inviterId, inviteeId));
							} else {
								if (null == flag) {
									WfPhoneCodeEntity pce = new WfPhoneCodeEntity();
									pce.setCode(code);
									pce.setPhone(mobile);
									Long time = System.currentTimeMillis() / 1000;
									pce.setSendTime(time.intValue());
									phoneCodeService.save(pce);
									memberService.delete(memberEntity.getUserid());
									return R.error(70, "");//课程已经被别人领过了，提示；
								}
							}
						}
					}
					//判断邀请人id是否为空，若不为空，则添加邀请记录
					WfMemberInvitationEntity memberInvitationEntity = new WfMemberInvitationEntity();
					memberInvitationEntity.setInviterid(inviterId);
					memberInvitationEntity.setInvitedid(memberEntity.getUserid());
					memberInvitationEntity.setCreatetime(new Date());
					memberInvitationService.save(memberInvitationEntity);

					//奖励给邀请人 ‘邀请新人奖励券’
					WfMemberCouponsEntity memberCouponsEntity = new WfMemberCouponsEntity();
					memberCouponsEntity.setUserid(inviterId);
					memberCouponsEntity.setTitle("邀请新人奖励券");
					memberCouponsEntity.setCost(20);
					memberCouponsEntity.setFtype(300);
					memberCouponsEntity.setLimits(1);
					memberCouponsEntity.setBeginDate(new Date());
					Date endDate = DateUtil.getNextMonth(new Date(), 1);
					memberCouponsEntity.setEndDate(endDate);
					memberCouponsEntity.setUpdateTime(new Date());
					memberCouponsEntity.setStatus(2);
					memberCouponsEntity.setCouponsSource(3);
					memberCouponsEntity.setReceiveTime(new Date());
					memberCouponsService.save(memberCouponsEntity);
				}

 				//奖励给新人满减券
				WfMemberCouponsEntity memberCouponsEntity = new WfMemberCouponsEntity();
				memberCouponsEntity.setUserid(Integer.valueOf(memberEntity.getUserid()));
				memberCouponsEntity.setTitle("新人注册满减券");
				memberCouponsEntity.setCost(20);
				memberCouponsEntity.setFtype(300);
				memberCouponsEntity.setLimits(1);
				memberCouponsEntity.setBeginDate(new Date());
				Date endDate = DateUtil.getNextDate(new Date(), 7);
				memberCouponsEntity.setEndDate(endDate);
				memberCouponsEntity.setUpdateTime(new Date());
				memberCouponsEntity.setStatus(2);
				memberCouponsEntity.setCouponsSource(100);
				memberCouponsEntity.setReceiveTime(new Date());
				memberCouponsService.save(memberCouponsEntity);
				couponFlag = 1;

 				WfMemberChildrenEntity memberChildrenEntity = new WfMemberChildrenEntity();
 				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 				memberChildrenEntity.setChildbirthday(sdf.format(new Date()));
 				memberChildrenEntity.setChildname("姓名_"+chineseName);
 				memberChildrenEntity.setChildsex(1);//性别默认为男（1、男 ； 2、女）
 				memberChildrenEntity.setUpdatetime(new Date());
 				memberChildrenEntity.setUserid(memberEntity.getUserid());
 				memberChildrenEntity.setRegion("北京市");
 				memberChildrenService.save(memberChildrenEntity);
  			}
 			result.put("token", ISsoLoginHelper.login(memberEntity.getUserid()));
 			result.put("memberEntity", memberEntity);
			WfCommenmanagerEntity commenmanager = commenmanagerService.queryObject(memberEntity.getUserid());

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
			String  startTime = sdf.format(new Date());
			String  endTime = sdf.format(DateUtil.getNextDate(new Date(), 7));
			result.put("couponFlag", couponFlag);//是否优惠券提示
			result.put("startTime", startTime);
			result.put("endTime", endTime);

			if(commenmanager == null){
				result.put("flag", 0);
			}else{
				result.put("flag", 1);
			}
 		}
		return result;
	}

	 /**
	 * 微信登录
	 */
	@RequestMapping("/wxlog")
	@ResponseBody
	@IgnoreToken
	public R wxlog(HttpServletRequest req) {
		R result = new R();
		String tokenId = req.getParameter("tokenId");//微信用户唯一标识
		//判断用户是否存在
		WfMemberEntity  memberEntity =  memberService.queryByIdentity(tokenId);
		String token = null;//用户token
		if(memberEntity != null){
//			token = String.valueOf(memberSessionService.createToken(memberEntity.getUserid()).get("token"));
            result.put("token", ISsoLoginHelper.login(memberEntity.getUserid()));
			result.put("memberEntity", memberEntity);
			WfCommenmanagerEntity commenmanager = commenmanagerService.queryObject(memberEntity.getUserid());
			if(commenmanager == null){
				result.put("flag", 0);
			}else{
				result.put("flag", 1);
			}
			return result;
		}
		return result;
	}

	/**
	 * 微信登录
	 */
	@RequestMapping("/newWxlog")
	@ResponseBody
	@IgnoreToken
	public R newWxlog(HttpServletRequest req) {
		R result = new R();
		String tokenId = req.getParameter("tokenId");//微信用户唯一标识
		String headImgUrl = req.getParameter("headImgUrl");//微信头像
		String openId = req.getParameter("openId");//微信用户唯一标识
		String nickname = req.getParameter("nickname");//微信昵称
		//判断用户是否存在
        System.out.println("********************tokenId:"+tokenId);
		WfMemberEntity  memberEntity =  memberService.queryByIdentity(tokenId);
		String token = null;//用户token
		if(memberEntity != null){
//			token = String.valueOf(memberSessionService.createToken(memberEntity.getUserid()).get("token"));
			memberEntity.setWxheadimage(headImgUrl);
			memberEntity.setWxopenid(openId);
			memberEntity.setWxnikename(nickname);
			memberService.update(memberEntity);
			result.put("token", ISsoLoginHelper.login(memberEntity.getUserid()));
			result.put("memberEntity", memberEntity);
			WfCommenmanagerEntity commenmanager = commenmanagerService.queryObject(memberEntity.getUserid());
			if(commenmanager == null){
				result.put("flag", 0);
			}else{
				result.put("flag", 1);
			}
			return result;
		}
		return result;
	}

	 /**
	 * 根据uid获取用户信息
	 */
	@RequestMapping("/getMember")
	@ResponseBody
	@IgnoreToken
	public R getMember(HttpServletRequest req) {
		String uid = req.getParameter("uid");//微信用户唯一标识
		System.out.println("***************uid:"+uid);
		//判断用户是否存在
		WfMemberEntity  memberEntity =  new WfMemberEntity();
		if(null == uid || "null".equals(uid) || "".equals(uid.trim())) {
		}else{
			memberEntity =  memberService.queryObject(Integer.valueOf(uid));
		}
		return R.ok().put("member", memberEntity);
	}

	/**
	 * 根据用户注册天数in
	 */
	@RequestMapping("/getDays")
	@ResponseBody
	public R getDays(HttpServletRequest req) {
		Integer uid = ISsoLoginHelper.confirm(req);//信用户唯一标识
		//判断用户是否存在
		WfMemberEntity  memberEntity =  new WfMemberEntity();
		long day=0;
		if(null != uid) {
			memberEntity =  memberService.queryObject(Integer.valueOf(uid));
			long createTime =  memberEntity.getCreatetime().getTime();
			long now =  new Date().getTime();
			day = (now- createTime) / (24 * 60 * 60 * 1000);
		}
		return R.ok().put("day", day);
	}

	 /**
	 * 微信登录绑定手机号
	 */
	@RequestMapping("/wxRegister")
	@ResponseBody
	@IgnoreToken
	public R wxRegister(HttpServletRequest req) {
		R result = new R();
		String tokenId = req.getParameter("tokenId");//微信用户唯一标识
		String mobile = req.getParameter("mobile");
		String code =  req.getParameter("code");//获取手机验证码
		String inviterId =  req.getParameter("inviterId");//邀请人id
 		log.debug("mobile:"+mobile);
 		log.debug("mobile:"+code);
		//判断验证码是否正确
 		Map<String,String> map =new  HashMap<String,String>();
 		map.put("mobile", mobile);
 		map.put("code", code);
 		WfPhoneCodeEntity phoneCodeEntity =  phoneCodeService.queryPhoneCode(map);

		if("606606".equals(code)) {
			phoneCodeEntity =  new WfPhoneCodeEntity();
		}

		int couponFlag = 0;
 		if(phoneCodeEntity == null) {
 			return R.error(67,"验证码错误");
 		}else {
 			//删除验证码记录
 	 		phoneCodeService.deleteByPhone(phoneCodeEntity.getPhone());
 		}
		//判断用户是否存在,若存在加入增加微信标识即可
		WfMemberEntity  memberEntity =  memberService.queryByMobile(mobile);
		String token = null;//用户token
		if(memberEntity == null){
 			//若第一次登陆，则生成新用户
			memberEntity = new WfMemberEntity();
			memberEntity.setTelephone(mobile);
			memberEntity.setStatus(1);//状态默认为启用
			memberEntity.setCreatetime(new Date());
			memberEntity.setUpdatetime(new Date());
			String chineseName = getStringRandom(6);//随机名字
			memberEntity.setUsername("姓名_"+chineseName);
			String userPassword = DigestUtils.md5Hex("123456");
			memberEntity.setUserpassword(userPassword);
			memberEntity.setBlackflag(0);
			memberEntity.setIdentity(tokenId);
			memberService.save(memberEntity);

			memberEntity = memberService.queryByMobile(mobile);

			/**
			 * 大礼包赠送课程（新用户）
			 */
			List<MemberGift> list = memberService.searchGift(mobile);
			if (list.size() > 0) {
				Integer userId = memberEntity.getUserid();
				String orderCode = DateUtil.getOrderNum();
				goodsOrderService.save(WfGoodsOrderEntity.generateFreeEntity(userId, orderCode));
				list.stream().forEach((item) -> {
					memberService.updateGift(item.getId());
					goodsOrderRelationService.save(WfGoodsOrderRelationEntity.generateFreeEntity
							(userId, orderCode, item.getCourseId(), item.getCourseType()));
				});
			}

			if(null != inviterId) {//判断邀请人id是否为空，若不为空，则添加邀请记录
				WfMemberInvitationEntity memberInvitationEntity = new WfMemberInvitationEntity();
				memberInvitationEntity.setInvitedid(Integer.valueOf(inviterId));
				memberInvitationEntity.setInvitedid(memberEntity.getUserid());
				memberInvitationEntity.setCreatetime(new Date());
				memberInvitationService.save(memberInvitationEntity);

				//奖励给邀请人 ‘邀请新人奖励券’
				WfMemberCouponsEntity memberCouponsEntity = new WfMemberCouponsEntity();
				memberCouponsEntity.setUserid(Integer.valueOf(inviterId));
				memberCouponsEntity.setTitle("邀请新人奖励券");
				memberCouponsEntity.setCost(20);
				memberCouponsEntity.setFtype(300);
				memberCouponsEntity.setLimits(1);
				memberCouponsEntity.setBeginDate(new Date());
				Date endDate = DateUtil.getNextMonth(new Date(), 1);
				memberCouponsEntity.setEndDate(endDate);
				memberCouponsEntity.setUpdateTime(new Date());
				memberCouponsEntity.setStatus(2);
				memberCouponsEntity.setCouponsSource(3);
				memberCouponsEntity.setReceiveTime(new Date());
				memberCouponsService.save(memberCouponsEntity);
			}

			//奖励给新人满减券
			WfMemberCouponsEntity memberCouponsEntity = new WfMemberCouponsEntity();
			memberCouponsEntity.setUserid(Integer.valueOf(memberEntity.getUserid()));
			memberCouponsEntity.setTitle("新人注册满减券");
			memberCouponsEntity.setCost(20);
			memberCouponsEntity.setFtype(300);
			memberCouponsEntity.setLimits(1);
			memberCouponsEntity.setBeginDate(new Date());
			Date endDate = DateUtil.getNextDate(new Date(), 7);
			memberCouponsEntity.setEndDate(endDate);
			memberCouponsEntity.setUpdateTime(new Date());
			memberCouponsEntity.setStatus(2);
			memberCouponsEntity.setCouponsSource(100);
			memberCouponsEntity.setReceiveTime(new Date());
			memberCouponsService.save(memberCouponsEntity);
			couponFlag = 1;

			WfMemberChildrenEntity memberChildrenEntity = new WfMemberChildrenEntity();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			memberChildrenEntity.setChildbirthday(sdf.format(new Date()));
			memberChildrenEntity.setChildname("姓名_"+chineseName);
			memberChildrenEntity.setChildsex(1);//性别默认为男（1、男 ； 2、女）
			memberChildrenEntity.setUpdatetime(new Date());
			memberChildrenEntity.setUserid(memberEntity.getUserid());
			memberChildrenEntity.setRegion("北京市");
			memberChildrenService.save(memberChildrenEntity);
		}else if(memberEntity != null && (memberEntity.getIdentity() == null || "".equals(memberEntity.getIdentity()))) {
			memberEntity.setIdentity(tokenId);
			memberService.update(memberEntity);
		}else{
			return R.error(66,"您的手机号已被其它微信绑定");
		}
//		token = String.valueOf(memberSessionService.createToken(memberEntity.getUserid()).get("token"));
		//返回token和用户信息
		result.put("token", ISsoLoginHelper.login(memberEntity.getUserid()));
		result.put("memberEntity", memberEntity);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String  startTime = sdf.format(new Date());
		String  endTime = sdf.format(DateUtil.getNextDate(new Date(), 7));
		result.put("couponFlag", couponFlag);//是否优惠券提示
		result.put("startTime", startTime);
		result.put("endTime", endTime);

		WfCommenmanagerEntity commenmanager = commenmanagerService.queryObject(memberEntity.getUserid());
		if(commenmanager == null){
			result.put("flag", 0);
		}else{
			result.put("flag", 1);
		}
		return result;
	}

	/**
	 * 微信登录绑定手机号(添加微信头像)
	 */
	@RequestMapping("/newWxRegister")
	@ResponseBody
	@IgnoreToken
	public R newWxRegister(HttpServletRequest req) {
		R result = new R();
		String tokenId = req.getParameter("tokenId");//微信用户唯一标识
		String mobile = req.getParameter("mobile");
		String code =  req.getParameter("code");//获取手机验证码
		String inviterId =  req.getParameter("inviterId");//邀请人id
		String headImgUrl = req.getParameter("headImgUrl");//微信头像
		String openId = req.getParameter("openId");//微信用户唯一标识
		String nickname = req.getParameter("nickname");//微信昵称
		log.debug("mobile:"+mobile);
		log.debug("mobile:"+code);
		//判断验证码是否正确
		Map<String,String> map =new  HashMap<String,String>();
		map.put("mobile", mobile);
		map.put("code", code);
		WfPhoneCodeEntity phoneCodeEntity =  phoneCodeService.queryPhoneCode(map);
		int couponFlag = 1;
		if(phoneCodeEntity == null) {
			return R.error(67,"验证码错误");
		}else {
			//删除验证码记录
			phoneCodeService.deleteByPhone(phoneCodeEntity.getPhone());
		}
		//判断用户是否存在,若存在加入增加微信标识即可
		WfMemberEntity  memberEntity =  memberService.queryByMobile(mobile);
		String token = null;//用户token
		if(memberEntity == null){
			//若第一次登陆，则生成新用户
			memberEntity = new WfMemberEntity();
			memberEntity.setTelephone(mobile);
			memberEntity.setStatus(1);//状态默认为启用
			memberEntity.setCreatetime(new Date());
			memberEntity.setUpdatetime(new Date());
			String chineseName = getStringRandom(6);//随机名字
			memberEntity.setUsername("姓名_"+chineseName);
			String userPassword = DigestUtils.md5Hex("123456");
			memberEntity.setUserpassword(userPassword);
			memberEntity.setBlackflag(0);
			memberEntity.setIdentity(tokenId);
			memberEntity.setWxheadimage(headImgUrl);
			memberEntity.setWxopenid(openId);
			memberEntity.setWxnikename(nickname);
			memberService.save(memberEntity);

			memberEntity = memberService.queryByMobile(mobile);

			/**
			 * 大礼包赠送课程（新用户）
			 */
			List<MemberGift> list = memberService.searchGift(mobile);
			if (list.size() > 0) {
				Integer userId = memberEntity.getUserid();
				String orderCode = DateUtil.getOrderNum();
				goodsOrderService.save(WfGoodsOrderEntity.generateFreeEntity(userId, orderCode));
				list.stream().forEach((item) -> {
					memberService.updateGift(item.getId());
					goodsOrderRelationService.save(WfGoodsOrderRelationEntity.generateFreeEntity
							(userId, orderCode, item.getCourseId(), item.getCourseType()));
				});
			}

			if(null != inviterId) {//判断邀请人id是否为空，若不为空，则添加邀请记录
				WfMemberInvitationEntity memberInvitationEntity = new WfMemberInvitationEntity();
				memberInvitationEntity.setInvitedid(Integer.valueOf(inviterId));
				memberInvitationEntity.setInvitedid(memberEntity.getUserid());
				memberInvitationEntity.setCreatetime(new Date());
				memberInvitationService.save(memberInvitationEntity);

				//奖励给邀请人 ‘邀请新人奖励券’
				WfMemberCouponsEntity memberCouponsEntity = new WfMemberCouponsEntity();
				memberCouponsEntity.setUserid(Integer.valueOf(inviterId));
				memberCouponsEntity.setTitle("邀请新人奖励券");
				memberCouponsEntity.setCost(20);
				memberCouponsEntity.setFtype(300);
				memberCouponsEntity.setLimits(1);
				memberCouponsEntity.setBeginDate(new Date());
				Date endDate = DateUtil.getNextMonth(new Date(), 1);
				memberCouponsEntity.setEndDate(endDate);
				memberCouponsEntity.setUpdateTime(new Date());
				memberCouponsEntity.setStatus(2);
				memberCouponsEntity.setCouponsSource(3);
				memberCouponsEntity.setReceiveTime(new Date());
				memberCouponsService.save(memberCouponsEntity);
			}

			//奖励给新人满减券
			WfMemberCouponsEntity memberCouponsEntity = new WfMemberCouponsEntity();
			memberCouponsEntity.setUserid(Integer.valueOf(memberEntity.getUserid()));
			memberCouponsEntity.setTitle("新人注册满减券");
			memberCouponsEntity.setCost(20);
			memberCouponsEntity.setFtype(300);
			memberCouponsEntity.setLimits(1);
			memberCouponsEntity.setBeginDate(new Date());
			Date endDate = DateUtil.getNextDate(new Date(), 7);
			memberCouponsEntity.setEndDate(endDate);
			memberCouponsEntity.setUpdateTime(new Date());
			memberCouponsEntity.setStatus(2);
			memberCouponsEntity.setCouponsSource(100);
			memberCouponsEntity.setReceiveTime(new Date());
			memberCouponsService.save(memberCouponsEntity);
			couponFlag = 0;

			WfMemberChildrenEntity memberChildrenEntity = new WfMemberChildrenEntity();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			memberChildrenEntity.setChildbirthday(sdf.format(new Date()));
			memberChildrenEntity.setChildname("姓名_"+chineseName);
			memberChildrenEntity.setChildsex(1);//性别默认为男（1、男 ； 2、女）
			memberChildrenEntity.setUpdatetime(new Date());
			memberChildrenEntity.setUserid(memberEntity.getUserid());
			memberChildrenEntity.setRegion("北京市");
			memberChildrenService.save(memberChildrenEntity);
		}else if(memberEntity != null && (memberEntity.getIdentity() == null || "".equals(memberEntity.getIdentity()))) {
			if(memberEntity.getWxheadimage()==null) {
				memberEntity.setWxheadimage(headImgUrl);
				memberEntity.setWxopenid(openId);
				memberEntity.setWxnikename(nickname);
			}
			memberEntity.setIdentity(tokenId);
			memberService.update(memberEntity);
		}else{
			return R.error(66,"您的手机号已被其它微信绑定");
		}
//		token = String.valueOf(memberSessionService.createToken(memberEntity.getUserid()).get("token"));
		//返回token和用户信息
		result.put("token", ISsoLoginHelper.login(memberEntity.getUserid()));
		result.put("memberEntity", memberEntity);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String  startTime = sdf.format(new Date());
		String  endTime = sdf.format(DateUtil.getNextDate(new Date(), 7));
		result.put("couponFlag", couponFlag);//是否优惠券提示
		result.put("startTime", startTime);
		result.put("endTime", endTime);

		WfCommenmanagerEntity commenmanager = commenmanagerService.queryObject(memberEntity.getUserid());
		if(commenmanager == null){
			result.put("flag", 0);
		}else{
			result.put("flag", 1);
		}
		return result;
	}


    /**
     * 最新微信登录绑定手机号,合并手机号用户数据
     */
    @RequestMapping("/mergeMember")
    @ResponseBody
    @IgnoreToken
    public R mergeMember(HttpServletRequest req) {
        String mobile = req.getParameter("mobile");
        String code =  req.getParameter("code");//获取手机验证码
        //判断验证码是否正确
        Map<String,String> map1 =new  HashMap();
        map1.put("mobile", mobile);
        map1.put("code", code);

        WfPhoneCodeEntity phoneCodeEntity =  phoneCodeService.queryPhoneCode(map1);
		if("606606".equals(code)) {
			phoneCodeEntity =  new WfPhoneCodeEntity();
		}
        if(phoneCodeEntity == null) {
            return R.error(67,"验证码错误");
        }else {
            //删除验证码记录
            phoneCodeService.deleteByPhone(phoneCodeEntity.getPhone());
        }
        //判断用户是否存在,若存在加入增加微信标识即可
        WfMemberEntity  memberEntity =  memberService.queryByMobile(mobile);

        //获取用户信息
        Integer uid = ISsoLoginHelper.confirm(req);
        WfMemberEntity  member = memberService.queryObject(Integer.valueOf(uid));

        if( null == memberEntity){
            member.setTelephone(mobile);
            memberService.update(member);
        }else if(memberEntity != null && (memberEntity.getIdentity() == null || "".equals(memberEntity.getIdentity()))) {
            //合并数据
            Map<String,Object> map =new  HashMap<String,Object>();
            Integer vuid = memberEntity.getUserid();//被合并用户id
            map.put("uid", vuid);

			Map<String, Object> mc = new HashMap<String, Object>();
			mc.put("userId", vuid);
			mc.put("status", 2);
			mc.put("out", 2);//是否过期 （1，是；2，否）

			List<WfMemberCouponsEntity> resultList = memberCouponsService.queryList(mc);
			for (int i = 0; i < resultList.size(); i++) {
				WfMemberCouponsEntity coupon = resultList.get(i);
				coupon.setUserid(uid);
				memberCouponsService.update(coupon);//挪优惠券
			}

			//获取订单
			List<WfGoodsOrderEntity> gOrderList = goodsOrderService.queryByUserId(vuid);
			for (int i = 0; i < gOrderList.size(); i++) {
				WfGoodsOrderEntity goodsOrderEntity = gOrderList.get(i);
				goodsOrderEntity.setUserid(uid);
				goodsOrderService.update(goodsOrderEntity);
			}
			List<WfGoodsOrderRelationEntity> goodsCourseList = goodsOrderRelationService.queryList(map);//获取订单关联数据
			for (int m = 0; m < goodsCourseList.size(); m++) {
				WfGoodsOrderRelationEntity course = goodsCourseList.get(m);
				course.setUserid(uid);
				goodsOrderRelationService.update(course);
			}

			//获取铜钱总数
			List<WfCoinLogEntity> coinLogList = coinLogService.queryList(map);
			for (int k = 0; k < coinLogList.size(); k++) {
				WfCoinLogEntity coinLogEntity = coinLogList.get(k);
				coinLogEntity.setUserid(uid);
				coinLogService.update(coinLogEntity);
			}

			//金币
			List<WfMemberGoldLogEntity> memberGoldLogList = memberGoldLogService.queryList(map);
			for (int i = 0; i < memberGoldLogList.size(); i++) {
				WfMemberGoldLogEntity memberGoldLog = memberGoldLogList.get(i);
				memberGoldLog.setUserid(uid);
				memberGoldLogService.update(memberGoldLog);
			}

			//新金币
			List<WfMemberNewGoldLogEntity> memberNewGoldLogList = memberNewGoldLogService.queryList(map);
			for (int i = 0; i < memberNewGoldLogList.size(); i++) {
				WfMemberNewGoldLogEntity memberNewGoldLog = memberNewGoldLogList.get(i);
				memberNewGoldLog.setUserid(uid);
				memberNewGoldLogService.update(memberNewGoldLog);
			}

			//新铜钱
			List<WfMemberGiveCoinLogEntity> memberberGiveCoinLogList = memberGiveCoinLogService.queryList(map);
			for (int i = 0; i < memberberGiveCoinLogList.size(); i++) {
				WfMemberGiveCoinLogEntity memberberGiveCoinLog = memberberGiveCoinLogList.get(i);
				memberberGiveCoinLog.setUserid(uid);
				memberGiveCoinLogService.update(memberberGiveCoinLog);
			}

			//邀请关系
			Map<String, Object> map3 = new HashMap<>();
			map3.put("inviterId", vuid);
			List<WfMemberInvitationEntity> invitationList = invitationService.queryList(map3);
			for (int i = 0; i < invitationList.size(); i++) {
				WfMemberInvitationEntity  invitation =  invitationList.get(i);
				invitation.setInviterid(uid);
				memberInvitationService.update(invitation);
			}

			Map<String, Object> map4 = new HashMap<>();
			map4.put("invitedId", vuid);
			List<WfMemberInvitationEntity> invitedList = invitationService.queryList(map4);
			for (int i = 0; i < invitedList.size(); i++) {
				WfMemberInvitationEntity  invitation =  invitedList.get(i);
				invitation.setInvitedid(uid);
				memberInvitationService.update(invitation);
			}

			//作业
			List<CourseWork>  courseWorkList= courseWorkService.queryMyCourseWork(vuid);
			for (int i = 0; i < courseWorkList.size(); i++) {
				CourseWork cw = courseWorkList.get(i);
				cw.setUserId(uid);
				courseWorkService.updateMemberWork(cw);
			}

			//拼团  团员
			List<WfCollageOrderEntity> collageList = collageOrderService.queryListByToUserId(vuid.toString());
			for (int i = 0; i < collageList.size(); i++) {
				WfCollageOrderEntity co = collageList.get(i);
				co.setTouserid(uid);
				collageOrderService.update(co);
			}
             //团长
			List<WfCollageOrderEntity> coList = collageOrderService.queryListByUserId(vuid.toString());
			for (int i = 0; i < coList.size(); i++) {
				WfCollageOrderEntity co = coList.get(i);
				co.setUserid(uid);
				collageOrderService.update(co);
			}

			//购物车
			Map<String, Object> map5 = new HashMap<>();
			map5.put("userId", vuid);
			List<WfShoppingCartEntity> shoppingCarList = shoppingCartService.queryList(map5);
			for (int i = 0; i <shoppingCarList.size() ; i++) {
				WfShoppingCartEntity sc = shoppingCarList.get(i);
				sc.setUserid(uid);
				shoppingCartService.update(sc);
			}

			//听课时长合并
			member.setStudyTime(member.getStudyTime()+ memberEntity.getStudyTime());
			member.setTelephone(mobile);
			memberService.update(member);

			memberService.delete(memberEntity.getUserid());
		}else{
            return R.error(66,"您的手机号已被其它微信绑定");
        }

        return R.ok();
    }

	/**
	 * 手机号绑定微信登录
	 */
	@RequestMapping("/telRegister")
	@ResponseBody
	@IgnoreToken
	public R telRegister(HttpServletRequest req) {
		R result = new R();
		String tokenId = req.getParameter("tokenId");//微信用户唯一标识
		String mobile = req.getParameter("mobile");
 		log.debug("mobile:"+mobile);
		//判断验证码是否正确
 		Map<String,String> map =new  HashMap<String,String>();
 		map.put("mobile", mobile);
		//判断用户是否存在,若存在加入增加微信标识即可
		WfMemberEntity  memberEntity =  memberService.queryByMobile(mobile);
		WfMemberEntity  memberToken =  memberService.queryByIdentity(tokenId);
		if(memberToken == null) {
			memberEntity.setIdentity(tokenId);
			memberService.update(memberEntity);

			//返回token和用户信息
			result.put("memberEntity", memberEntity);
			WfCommenmanagerEntity commenmanager = commenmanagerService.queryObject(memberEntity.getUserid());
			if(commenmanager == null){
				result.put("flag", 0);
			}else{
				result.put("flag", 1);
			}
			return result;
		}
		return R.error(63,"微信已被其他手机号绑定");
	}

	/**
	 * 手机号绑定微信登录
	 */
	@RequestMapping("/newTelRegister")
	@ResponseBody
	@IgnoreToken
	public R newTelRegister(HttpServletRequest req) {
		R result = new R();
		String tokenId = req.getParameter("tokenId");//微信用户唯一标识
		String mobile = req.getParameter("mobile");
		String headImgUrl = req.getParameter("headImgUrl");//微信头像
		String openId = req.getParameter("openId");//微信用户唯一标识
		String nickname = req.getParameter("nickname");//微信昵称
		log.debug("mobile:"+mobile);
		//判断验证码是否正确
		Map<String,String> map =new  HashMap<String,String>();
		map.put("mobile", mobile);
		//判断用户是否存在,若存在加入增加微信标识即可
		WfMemberEntity  memberEntity =  memberService.queryByMobile(mobile);
		WfMemberEntity  memberToken =  memberService.queryByIdentity(tokenId);
		if(memberToken == null) {
			if(memberEntity.getWxheadimage()==null) {
				memberEntity.setWxheadimage(headImgUrl);
				memberEntity.setWxopenid(openId);
				memberEntity.setWxnikename(nickname);
			}
			memberEntity.setIdentity(tokenId);
			memberService.update(memberEntity);

			//返回token和用户信息
			result.put("memberEntity", memberEntity);
			WfCommenmanagerEntity commenmanager = commenmanagerService.queryObject(memberEntity.getUserid());
			if(commenmanager == null){
				result.put("flag", 0);
			}else{
				result.put("flag", 1);
			}
			return result;
		}
		return R.error(63,"微信已被其他手机号绑定");
	}

	/**
	 * 手机号绑定微信信息
	 */
	@RequestMapping("/bindWxInfo")
	@ResponseBody
	@IgnoreToken
	public R bindWxInfo(HttpServletRequest req) {
		R result = new R();
		String mobile = req.getParameter("mobile");
		String code = req.getParameter("code");
		String headImgUrl =  req.getParameter("headImgUrl");//微信头像
		if(StringUtils.isNotBlank(headImgUrl)){
			try {
				headImgUrl = URLDecoder.decode(headImgUrl,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		String openId = req.getParameter("openId");//微信用户唯一标识
		String nickname = req.getParameter("nickname");//微信昵称
		String unionId = req.getParameter("unionId");//微信用户唯一标识
		String inviteId = req.getParameter("inviteId");//邀请人
		log.debug("mobile:"+mobile);

		//判断验证码是否正确
		Map<String,String> map =new  HashMap<>();
		map.put("mobile", mobile);
		map.put("code", code);
		WfPhoneCodeEntity phoneCodeEntity =  phoneCodeService.queryPhoneCode(map);

		if("606606".equals(code)) {
			phoneCodeEntity =  new WfPhoneCodeEntity();
		}
		if(phoneCodeEntity == null) {
			return R.error(67,"验证码错误");
		}else {
			//判断用户是否存在,若存在加入增加微信标识即可
			WfMemberEntity  telMember =  memberService.queryByMobile(mobile);

			if( null == telMember){
				//注册手机微信用户
				WfMemberEntity member = new WfMemberEntity();//创建新用户

				member.setTelephone(mobile);
				member.setStatus(1);//状态默认为启用
				member.setCreatetime(new Date());
				member.setUpdatetime(new Date());
				member.setUsername(nickname);
				String userPassword = DigestUtils.md5Hex("123456");
				member.setUserpassword(userPassword);
				member.setBlackflag(0);
				member.setWxheadimage(headImgUrl);
				member.setWxopenid(openId);
				member.setWxnikename(nickname);
				member.setIdentity(unionId);
				member.setStudyTime(0);
				System.out.println("注册wxmember:------------------"+member.toString());
				memberService.save(member);
				member =  memberService.queryByIdentity(unionId);

				if(!"".equals(inviteId.trim()) && null != inviteId) {
					//判断邀请人id是否为空，若不为空，则添加邀请记录
					WfMemberInvitationEntity memberInvitationEntity = new WfMemberInvitationEntity();
					memberInvitationEntity.setInviterid(Integer.valueOf(inviteId));
					memberInvitationEntity.setInvitedid(member.getUserid());
					memberInvitationEntity.setCreatetime(new Date());
					memberInvitationService.save(memberInvitationEntity);

					//奖励给邀请人 ‘邀请新人奖励券’
					WfMemberCouponsEntity memberCouponsEntity = new WfMemberCouponsEntity();
					memberCouponsEntity.setUserid(Integer.valueOf(inviteId));
					memberCouponsEntity.setTitle("邀请新人奖励券");
					memberCouponsEntity.setCost(20);
					memberCouponsEntity.setFtype(300);
					memberCouponsEntity.setLimits(1);
					memberCouponsEntity.setBeginDate(new Date());
					Date endDate = DateUtil.getNextMonth(new Date(), 1);
					memberCouponsEntity.setEndDate(endDate);
					memberCouponsEntity.setUpdateTime(new Date());
					memberCouponsEntity.setStatus(2);
					memberCouponsEntity.setCouponsSource(3);
					memberCouponsEntity.setReceiveTime(new Date());
					memberCouponsService.save(memberCouponsEntity);
				}

				//奖励给新人满减券
				WfMemberCouponsEntity memberCouponsEntity = new WfMemberCouponsEntity();
				memberCouponsEntity.setUserid(Integer.valueOf(member.getUserid()));
				memberCouponsEntity.setTitle("新人注册满减券");
				memberCouponsEntity.setCost(20);
				memberCouponsEntity.setFtype(300);
				memberCouponsEntity.setLimits(1);
				memberCouponsEntity.setBeginDate(new Date());
				Date endDate = DateUtil.getNextDate(new Date(), 7);
				memberCouponsEntity.setEndDate(endDate);
				memberCouponsEntity.setUpdateTime(new Date());
				memberCouponsEntity.setStatus(2);
				memberCouponsEntity.setCouponsSource(100);
				memberCouponsEntity.setReceiveTime(new Date());
				memberCouponsService.save(memberCouponsEntity);

				WfMemberChildrenEntity memberChildrenEntity = new WfMemberChildrenEntity();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				memberChildrenEntity.setChildbirthday(sdf.format(new Date()));
				memberChildrenEntity.setChildname(nickname);
				memberChildrenEntity.setChildsex(1);//性别默认为男（1、男 ； 2、女）
				memberChildrenEntity.setUpdatetime(new Date());
				memberChildrenEntity.setUserid(member.getUserid());
				memberChildrenEntity.setRegion("北京市");
				memberChildrenService.save(memberChildrenEntity);

			}else if(null == telMember.getWxopenid() || null == telMember.getWxheadimage() || null == telMember.getIdentity() || null == telMember.getWxnikename()||
					0 == telMember.getWxopenid().trim().length() || 0 == telMember.getWxheadimage().trim().length() || 0 == telMember.getIdentity().trim().length() || 0 == telMember.getWxnikename().trim().length()){
				telMember.setWxheadimage(headImgUrl);
				telMember.setWxopenid(openId);
				telMember.setWxnikename(nickname);
				telMember.setIdentity(unionId);
				log.info("结合wxmember:------------------"+telMember.toString());
				memberService.update(telMember);
			}else{
				return R.error(66,"您的手机号已被其它微信绑定");
			}
			//返回token和用户信息
			WfMemberEntity  memberEntity =  memberService.queryByIdentity(unionId);
            result.put("token", ISsoLoginHelper.loginGetToken(memberEntity.getUserid()));
			result.put("memberEntity", memberEntity);
			return result;
		}
	}


	 /**
	 * 游客注册登录
	 */
	@RequestMapping("/visitorLogin")
	@IgnoreToken
	@ResponseBody
	public R visitorLogin(HttpServletRequest req) {
		R result = new R();

		String uuid =  req.getParameter("uuid");//游客标识
 		log.debug("uuid:"+uuid);
		//判断验证码是否正确
 		WfMemberEntity  member =  memberService.queryByIdentity(uuid);

 		Map<String,String> map =new  HashMap<String,String>();
 		map.put("uuid", uuid);
 		String token = "";
 		if(member == null) {
 			member = new WfMemberEntity();
 			member.setIdentity(uuid);
 			member.setStatus(1);//状态（0.停用 1.启用）
 			member.setCreatetime(new Date());
 			member.setBlackflag(0);//黑名单(1.是 0.否)
 			String userPassword = DigestUtils.md5Hex("123456");
 			member.setUserpassword(userPassword);
			memberService.save(member);
			member =  memberService.queryByIdentity(uuid);
		}
 		//返回token
 		result.put("token", ISsoLoginHelper.login(member.getUserid()));
 		return result;
 	}


	/**
	 * 微信游客绑定手机号
	 */
	@RequestMapping("/visitorBindMobile")
	@ResponseBody
	public R visitorBindMobile(HttpServletRequest req) {
		R result = new R();
		Integer uid = ISsoLoginHelper.confirm(req);//微信游客uid
		String mobile = req.getParameter("mobile");
		String inviterId = req.getParameter("inviterId");//邀请人id
		String code = req.getParameter("code");//验证码

		log.debug("mobile:"+mobile);
		//判断验证码是否正确

		//判断用户是否存在,若存在加入增加微信标识即可
		WfMemberEntity  memberEntity =  memberService.queryByMobile(mobile);
		WfMemberEntity  member =  memberService.queryObject(uid);

		int couponFlag=0;
		//判断验证码是否正确
		Map<String,String> map =new  HashMap<>();
		map.put("mobile", mobile);
		map.put("code", code);
		WfPhoneCodeEntity phoneCodeEntity =  phoneCodeService.queryPhoneCode(map);

		if("606606".equals(code)) {
			phoneCodeEntity =  new WfPhoneCodeEntity();
		}

		if(phoneCodeEntity == null) {
			return R.error(67,"验证码错误");
		}else {
			if(memberEntity == null) {
				member.setTelephone(mobile);
				memberService.update(member);//成功绑定手机号

				//绑定邀请人关系，赠送优惠券
				//判断邀请人id是否为空，若不为空，则添加邀请记录
				Integer inviter = (null == inviterId) ? 0 : Integer.valueOf(inviterId);
				Map<String, Object> map3 = new HashMap<String, Object>();
				map3.put("invitedId", uid);
				List<WfMemberInvitationEntity> invitationList = invitationService.queryList(map3);
				if (inviter != 0 && invitationList.size() == 0) { //邀请人不为空且用户没有被邀请记录
					WfMemberInvitationEntity memberInvitationEntity = new WfMemberInvitationEntity();
					memberInvitationEntity.setInviterid(inviter);
					memberInvitationEntity.setInvitedid(uid);
					memberInvitationEntity.setCreatetime(new Date());
					memberInvitationService.save(memberInvitationEntity);
				}

				//奖励给邀请人 ‘邀请新人奖励券’
				WfMemberCouponsEntity memberCouponsEntity = new WfMemberCouponsEntity();
				memberCouponsEntity.setUserid(inviter);
				memberCouponsEntity.setTitle("邀请新人奖励券");
				memberCouponsEntity.setCost(20);
				memberCouponsEntity.setFtype(300);
				memberCouponsEntity.setLimits(1);
				memberCouponsEntity.setBeginDate(new Date());
				Date endDate = DateUtil.getNextMonth(new Date(), 1);
				memberCouponsEntity.setEndDate(endDate);
				memberCouponsEntity.setUpdateTime(new Date());
				memberCouponsEntity.setStatus(2);
				memberCouponsEntity.setCouponsSource(3);
				memberCouponsEntity.setReceiveTime(new Date());
				memberCouponsService.save(memberCouponsEntity);
				couponFlag = 1;

				SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
				String startTime = sdf.format(new Date());
				String endTime = sdf.format(DateUtil.getNextDate(new Date(), 7));
				result.put("couponFlag", couponFlag);//是否优惠券提示
				result.put("startTime", startTime);
				result.put("endTime", endTime);

				//返回token和用户信息
				result.put("member", member);
				result.put("token", ISsoLoginHelper.login(member.getUserid()));

				WfCommenmanagerEntity commenmanager = commenmanagerService.queryObject(uid);
				if (commenmanager == null) {
					result.put("flag", 0);
				} else {
					result.put("flag", 1);
				}
				return result;
			}
		}
		return R.error(63,"手机号已被其他账户绑定，请您直接登录");
	}

	 /**
	 * 退出登录
	 */
	@RequestMapping("/logout")
	@ResponseBody
	public R logout(HttpServletRequest req) {
        ISsoLoginHelper.logout(req);
//		Integer uid = ISsoLoginHelper.confirm(req);
//		memberSessionService.delete(uid);
		return R.ok();
	}

	 /**
	 * 铜钱查询
	 */
	@RequestMapping("/myCoin")
	@ResponseBody
	public R myCoin(HttpServletRequest req) {
		Map<String,Object> map =new  HashMap<String,Object>();
		Integer uid = ISsoLoginHelper.confirm(req);
		//获取待付款个数
		map.put("uid", uid);
		//获取铜钱总数（原铜钱）
		//map.put("status", 2);
		//map.put("resource", 2);//（1.购物 2.邀请好友 3.充值）
		List<WfCoinLogEntity> coinLogList =  coinLogService.queryList(map);
		BigDecimal coins = new BigDecimal("0");
		for(int k = 0 ; k< coinLogList.size(); k++) {
			WfCoinLogEntity coinLogEntity = coinLogList.get(k);
			if(1 == coinLogEntity.getFlowflag() && coinLogEntity.getDeleteflag()==0) {
				coins = coins.add(coinLogEntity.getCoinvalue());
			}else if(2 == coinLogEntity.getFlowflag() && coinLogEntity.getDeleteflag()==0
					&& (coinLogEntity.getStatus()==1 || coinLogEntity.getStatus()==2 )){
				coins = coins.subtract(coinLogEntity.getCoinvalue());
			}
		}
		//查询新铜钱（邀请人消费后赠送的）
		List<WfMemberGiveCoinLogEntity> memberberGiveCoinLogList = memberGiveCoinLogService.queryList(map);
		for(int i=0; i<memberberGiveCoinLogList.size(); i++) {
			WfMemberGiveCoinLogEntity  memberberGiveCoinLog = memberberGiveCoinLogList.get(i);
			if(1 == memberberGiveCoinLog.getType()||3 == memberberGiveCoinLog.getType()) {
				coins = coins.add(memberberGiveCoinLog.getCoinvalue());
			}else if(2 == memberberGiveCoinLog.getType()
					&& (memberberGiveCoinLog.getStatus()==1 || memberberGiveCoinLog.getStatus()==2 )){
				coins = coins.subtract(memberberGiveCoinLog.getCoinvalue());
			}
		}
		//查询金币充值
		List<WfMemberGoldLogEntity> memberGoldLogList = memberGoldLogService.queryList(map);
		for(int i=0; i<memberGoldLogList.size(); i++) {
			WfMemberGoldLogEntity   memberGoldLog = memberGoldLogList.get(i);
			if(1 == memberGoldLog.getType() || 3 == memberGoldLog.getType()) {
				coins = coins.add(memberGoldLog.getGoldvalue());
			}else if(2 == memberGoldLog.getType()
					&& (memberGoldLog.getStatus()==1 || memberGoldLog.getStatus()==2 )){
				coins = coins.subtract(memberGoldLog.getGoldvalue());
			}
		}
		//查询新金币充值
		List<WfMemberNewGoldLogEntity> memberNewGoldLogList = memberNewGoldLogService.queryList(map);
		for(int i=0; i<memberNewGoldLogList.size(); i++) {
			WfMemberNewGoldLogEntity   memberNewGoldLog = memberNewGoldLogList.get(i);
			if(1 == memberNewGoldLog.getType() || 3 == memberNewGoldLog.getType()) {
				coins = coins.add(memberNewGoldLog.getGoldvalue());
			}else if(2 == memberNewGoldLog.getType()
					&& (memberNewGoldLog.getStatus()==1 || memberNewGoldLog.getStatus()==2 )){
				coins = coins.subtract(memberNewGoldLog.getGoldvalue());
			}
		}

		if(coins.compareTo(BigDecimal.ZERO) <= 0) {
			return R.ok().put("coins",new BigDecimal("0"));
		}
		return R.ok().put("coins",coins);
	}


	/**
	 * 铜钱查询 //测试用，看老铜钱有没有用完
	 */
	@RequestMapping("/myOldCoins")
	@ResponseBody
	@IgnoreToken
	public void myOldCoins(HttpServletRequest req) {

		List<WfMemberEntity> memberList =  memberService.queryList(null);
		for (int i = 0; i <memberList.size() ; i++) {
			Map<String,Object> map =new  HashMap<String,Object>();
			//获取待付款个数
			map.put("uid", memberList.get(i).getUserid());
			//获取铜钱总数（原铜钱）
			//map.put("status", 2);
			//map.put("resource", 2);//（1.购物 2.邀请好友 3.充值）
			List<WfCoinLogEntity> coinLogList =  coinLogService.queryList(map);
			BigDecimal coins = new BigDecimal("0");
			for(int k = 0 ; k< coinLogList.size(); k++) {
				WfCoinLogEntity coinLogEntity = coinLogList.get(k);
				if(1 == coinLogEntity.getFlowflag() && coinLogEntity.getDeleteflag()==0) {
					coins = coins.add(coinLogEntity.getCoinvalue());
				}else if(2 == coinLogEntity.getFlowflag() && coinLogEntity.getDeleteflag()==0
						&& (coinLogEntity.getStatus()==1 || coinLogEntity.getStatus()==2 )){
					coins = coins.subtract(coinLogEntity.getCoinvalue());
				}
			}
			if(coins.compareTo(BigDecimal.ZERO) != 0) {
				System.out.println("***uid:" + memberList.get(i).getUserid() + "      coins:" + coins);
			}
		}
	}

	 /**
	 * 收货信息
	 */
	@RequestMapping("/address")
	@ResponseBody
	public R address(HttpServletRequest req) {

		Integer uid = ISsoLoginHelper.confirm(req);
		WfMemberAddressEntity memberAddressEntity = memberAddressService.queryObject(uid);//根据UserId查询宝贝信息

		return R.ok().put("memberAddressEntity", memberAddressEntity);
	}

	 /**
	 * 更新收货信息
	 */
	@RequestMapping("/updateAddress")
	@ResponseBody
	public R updateAddress(HttpServletRequest req) {

		WfMemberAddressEntity memberAddressEntity = new WfMemberAddressEntity();

		Integer uid = ISsoLoginHelper.confirm(req);

		String recipient = req.getParameter("recipient");//收件人
		String contact = req.getParameter("contact");//联系方式
		String city = req.getParameter("city");//省市区
		String address = req.getParameter("address");//详细地址
		String postCode = "";//邮政编码
		memberAddressEntity.setUserid(uid);
		memberAddressEntity.setRecipient(recipient);
		memberAddressEntity.setContact(contact);
		memberAddressEntity.setCity(city);
		memberAddressEntity.setAddress(address);
		memberAddressEntity.setPostcode(postCode);
		memberAddressEntity.setUpdateTime(new Date());

		WfMemberAddressEntity memberAddress = memberAddressService.queryObject(uid);
		if(null == memberAddress) {
			memberAddressService.save(memberAddressEntity);
		}else {
			memberAddressService.update(memberAddressEntity);
		}
		return R.ok();
	}

	 /**
	 * 更新收货信息
	 */
	@RequestMapping("/updateAddressH5")
	@ResponseBody
	public R updateAddressH5(HttpServletRequest req,String recipient,String contact,String city,String address) {

		WfMemberAddressEntity memberAddressEntity = new WfMemberAddressEntity();
		Integer uid = ISsoLoginHelper.confirm(req);

		String postCode = "";
//		try {
//			recipient = new String(req.getParameter("recipient").getBytes("ISO8859-1"), "UTF-8");//收件人
//			contact = new String(req.getParameter("contact").getBytes("ISO8859-1"), "UTF-8");//联系方式
//			city = new String(req.getParameter("city").getBytes("ISO8859-1"), "UTF-8");//省市区
//			address = new String(req.getParameter("address").getBytes("ISO8859-1"), "UTF-8");//详细地址
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}

		memberAddressEntity.setUserid(uid);
		memberAddressEntity.setRecipient(recipient);
		memberAddressEntity.setContact(contact);
		memberAddressEntity.setCity(city);
		memberAddressEntity.setAddress(address);
		memberAddressEntity.setPostcode(postCode);
		memberAddressEntity.setUpdateTime(new Date());

		WfMemberAddressEntity memberAddress = memberAddressService.queryObject(uid);
		if(null == memberAddress) {
			memberAddressService.save(memberAddressEntity);
		}else {
			memberAddressService.update(memberAddressEntity);
		}
		return R.ok();
	}

	 /**
	 * 宝贝信息
	 */
	@RequestMapping("/children")
	@ResponseBody
	public R children(HttpServletRequest req) {
		R result = new R();
		Integer uid = ISsoLoginHelper.confirm(req);
		WfMemberEntity  member =  memberService.queryObject(uid);
		WfMemberChildrenEntity memberChildrenEntity = memberChildrenService.queryObject(uid);//根据UserId查询宝贝信息

		result.put("memberChildrenEntity", memberChildrenEntity);
		result.put("image", member.getHeadimage());
		return result;
	}

	 /**
	 * 更新宝贝信息
	 */
	@RequestMapping("/updateChildren")
	@ResponseBody
	public R updateChildren(HttpServletRequest req) {

		Integer uid = ISsoLoginHelper.confirm(req);
		WfMemberChildrenEntity	memberChildrenEntity = new WfMemberChildrenEntity();
		String childName = req.getParameter("childName");//收件人
		String childBirthday = req.getParameter("childBirthday");//出生年月
		String childSex = req.getParameter("childSex");//性别
		String city = req.getParameter("city");//省市区


		memberChildrenEntity.setChildbirthday(childBirthday);
		memberChildrenEntity.setChildname(childName);
		memberChildrenEntity.setChildsex(childSex != null ? Integer.valueOf(childSex) : null);//性别默认为男（1、男 ； 2、女）
		memberChildrenEntity.setUpdatetime(new Date());
		memberChildrenEntity.setUserid(uid);
		memberChildrenEntity.setRegion(city);

		WfMemberEntity  member =  memberService.queryObject(uid);//用户信息
		member.setUsername(StringUtils.isNotBlank(childName) ? childName : null);
		WfMemberChildrenEntity memberChildren = memberChildrenService.queryObject(uid);
		if(null == memberChildren) {
			memberChildrenService.save(memberChildrenEntity);
			memberService.update(member);
		}else {
			memberChildrenService.update(memberChildrenEntity);
			memberService.update(member);
		}
		return R.ok();
	}

	 /**
	 * 更新宝贝信息
	 */
	@RequestMapping("/updateChildrenH5")
	@ResponseBody
	public R updateChildrenH5(HttpServletRequest req,String childName,String childBirthday,String childSex,String city) {

		WfMemberChildrenEntity memberChildrenEntity = new WfMemberChildrenEntity();

		Integer uid = ISsoLoginHelper.confirm(req);
		
		memberChildrenEntity.setChildbirthday(childBirthday);
		memberChildrenEntity.setChildname(childName);
		memberChildrenEntity.setChildsex(childSex != null ? Integer.valueOf(childSex) : null);//性别默认为男（1、男 ； 2、女）
		memberChildrenEntity.setUpdatetime(new Date());
		memberChildrenEntity.setUserid(uid);
		memberChildrenEntity.setRegion(city);

		WfMemberEntity  member =  memberService.queryObject(uid);//用户信息
		member.setUsername(StringUtils.isNotBlank(childName) ? childName : null);
		WfMemberChildrenEntity memberChildren = memberChildrenService.queryObject(uid);
		if(null == memberChildren) {
			memberChildrenService.save(memberChildrenEntity);
			memberService.update(member);
		}else {
			memberChildrenService.update(memberChildrenEntity);
			memberService.update(member);
		}
		return R.ok();
	}

	 /**
	 * 获取用户id
	 */
	@RequestMapping("/getUserId")
	@ResponseBody
	public R getUserId(HttpServletRequest req) {

		Integer uid = ISsoLoginHelper.confirm(req);

		return R.ok().put("uid", uid);
	}


	 /**
	 * 判断token是否有效
	 */
	@RequestMapping("/confirm")
	@ResponseBody
	public R confirm(HttpServletRequest req) {

//		Integer uid = ISsoLoginHelper.confirm(req);
        Integer uid = ISsoLoginHelper.confirm(req);
		if(uid != null) {
			return R.ok();
		}else {
			return R.error(500, "令牌无效，请重新登录");
		}
	}


	 /**
	 * 省市获取
	 */
	@RequestMapping("/areaList")
	@ResponseBody
	@IgnoreToken
	public R areaList(HttpServletRequest req) {

		List<WfAreaEntity> areaList = new ArrayList<WfAreaEntity>();
		Map<String,Object> map =new  HashMap<String,Object>();
		areaList = areaService.queryList(map);

		return R.ok().put("areaList", areaList);
	}

	 /**
	 * 常见问题
	 */
	@RequestMapping("/question")
	@ResponseBody
	@IgnoreToken
	public R question(HttpServletRequest req) {

		List<WfQuestionEntity> questionList = new ArrayList<WfQuestionEntity>();
		Map<String,Object> map =new  HashMap<String,Object>();
		questionList = questionService.queryList(map);

		return R.ok().put("areaList", questionList);
	}

	/**
	 * 意见反馈
	 */
	@RequestMapping("/opinion")
	@ResponseBody
	public R opinion(HttpServletRequest req) {


		Integer uid = ISsoLoginHelper.confirm(req);
		/*Map<String,Object> map =new  HashMap<String,Object>();
		map.put("uid", uid);
		map.put("createTime", new Date());
		List<WfOpinionEntity>  opinionEntityList = opinionService.queryList(map);
		if(opinionEntityList.size()>3) {
			return R.error("亲，每天最多提交三次哦！");
		}else {*/
			WfOpinionEntity opinionEntity = new WfOpinionEntity();
			String remark = req.getParameter("remark");//意见内容
			//获取用户手机号
			WfMemberEntity  memberEntity = memberService.queryObject(uid);
			String mobile =  memberEntity.getTelephone();

			opinionEntity.setUserid(uid);
			opinionEntity.setRemark(remark);
			opinionEntity.setMobile(mobile);
			opinionEntity.setCreatetime(new Date());
			opinionService.save(opinionEntity);
		//}
		return R.ok();
	}

	/**
	 * 邀请人列表
	 */
	@RequestMapping("/getInvitedList")
	@ResponseBody
	public R getInvitedList(HttpServletRequest req) {

		Integer uid = ISsoLoginHelper.confirm(req);
		int page = Integer.valueOf(req.getParameter("page"));
		Map<String,Object> map =new  HashMap<String,Object>();
		map.put("inviterId", uid);
		int total =  memberInvitationService.queryTotal(map);
		map.put("page", page);
		//获取用户手机号
		Query query = new Query(map);
		List<WfMemberInvitationEntity> InvitedList  = memberInvitationService.queryinvited(query);
		//int total =  memberInvitationService.queryTotal(map);
		//获取用户手机号
		//List<WfMemberGiveCoinLogEntity> memberberGiveCoinLogList = memberGiveCoinLogService.queryList(map);

		/*Map<String,Object> resultMap =new  HashMap<String,Object>();
		resultMap.put("InvitedList", InvitedList);
		resultMap.put("memberberGiveCoinLogList", memberberGiveCoinLogList);*/

		Map<String,Object> result =new  HashMap<String,Object>();
		result.put("InvitedList", InvitedList);
		result.put("total", total);
		return R.ok(result);
	}

	/**
	 * 邀请人获取铜钱列表
	 */
	@RequestMapping("/getInvitedCoinsList")
	@ResponseBody
	public R getInvitedCoinsList(HttpServletRequest req) {

		Integer uid = ISsoLoginHelper.confirm(req);
		int page = Integer.valueOf(req.getParameter("page"));
		Map<String,Object> map =new  HashMap<String,Object>();
		map.put("uid", uid);
		BigDecimal coinValue = new BigDecimal("0");
		if(1 == page) {
			List<WfMemberInvitationViewCoinEntity> memberInvitationViewCoinList =  memberInvitationViewCoinService.queryList(map);
			for(int k = 0 ; k< memberInvitationViewCoinList.size(); k++) {
				WfMemberInvitationViewCoinEntity memberInvitationViewCoin = memberInvitationViewCoinList.get(k);
				coinValue = coinValue.add(memberInvitationViewCoin.getCoinvalue());
			}
		}
		int total =  memberInvitationViewCoinService.queryTotal(map);
		//获取原铜钱
		map.put("page", page);
		Query query = new Query(map);
		List<WfMemberInvitationViewCoinEntity> memberInvitationViewCoinList1 =  memberInvitationViewCoinService.queryList(query);
		Map<String,Object> map1 =new  HashMap<String,Object>();//保存铜钱信息和用户信息
		map1.put("coinValue", coinValue);
		map1.put("total", total);
		map1.put("memberInvitationViewCoinList", memberInvitationViewCoinList1);

		return R.ok(map1);
	}

    /**
     * 上传用户头像
     */
    @RequestMapping("/uploadPhoto")
    public R uploadPhoto(@RequestParam("imgFile") MultipartFile imgFile, HttpServletRequest req) throws Exception {
        if (imgFile.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        Integer uid = ISsoLoginHelper.confirm(req);
        WfMemberEntity member = memberService.queryObject(uid);

        String newsUrl = "";
        if (!((MultipartFile) imgFile).isEmpty()) {
            try {
                newsUrl = OSSUtil.addFile(imgFile, "head", Constants.IGM_BUCKET);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
        	return R.error("上传图片不可为空");
        }
        if(member.getHeadimage() == null) {
        	 member.setHeadimage(newsUrl);
             member.setThumbimg(newsUrl);
             memberService.update(member);
        }else {
        	// 删除原来图片
            OSSUtil.delete(member.getHeadimage(), Constants.IGM_BUCKET);
        	member.setHeadimage(newsUrl);
            member.setThumbimg(newsUrl);
            memberService.update(member);
        }
        System.out.println("*************************************头像路径： "+newsUrl+"***************************************");
        return R.ok().put("url", newsUrl);
    }

  /*  *//**
     * 上传bug文件
     */
    @RequestMapping("/uploadText")
    @IgnoreToken
    @IgnoreSign
    public R uploadText(@RequestParam("imgFile") MultipartFile imgFile, HttpServletRequest req) throws Exception {
        if (imgFile.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        String newsUrl = "";
        if (!((MultipartFile) imgFile).isEmpty()) {
            try {
                newsUrl = OSSUtil.addBugFile(imgFile, "bugtxt", Constants.IGM_BUCKET);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
        	return R.error("上传文件不可为空");
        }
        System.out.println("*************************************头像路径： "+newsUrl+"***************************************");
        return R.ok();
    }

	/*@RequestMapping("/uploadText")
	@IgnoreToken
	@IgnoreSign
	public R uploadText() throws Exception {

		String newsUrl = "";
		try {
			File baseFile = new File("C:\\Users\\zhenfang\\Desktop\\html");
			if (baseFile.isFile() || !baseFile.exists()) {
				return R.error(1,"是文件");
			}
			File[] files = baseFile.listFiles();
			for (File file : files) {
				newsUrl = OSSUtil.addBugFile(file, "server_image", Constants.IGM_BUCKET);
				System.out.println("头像路径： "+newsUrl+"***************************************");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}


		return R.ok();
	}*/



    @RequestMapping("/iosUpload")
   public R iosUpload(HttpServletRequest req){

    	Integer uid = ISsoLoginHelper.confirm(req);
        WfMemberEntity member = memberService.queryObject(uid);

    	String image = req.getParameter("image");
    	  // 将base64 转 字节数组
        Base64 base = new Base64();
        byte[] decode = base.decode(image);

        // 定义图片输入流
        InputStream fin = new ByteArrayInputStream(decode);

        String newsUrl = "";
        try {
            newsUrl = OSSUtil.putFile(fin, "head", Constants.IGM_BUCKET);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(member.getHeadimage() == null) {
        	 member.setHeadimage(newsUrl);
             member.setThumbimg(newsUrl);
             memberService.update(member);
        }else {
        	// 删除原来图片
            OSSUtil.delete(member.getHeadimage(), Constants.IGM_BUCKET);
        	member.setHeadimage(newsUrl);
            member.setThumbimg(newsUrl);
            memberService.update(member);
        }
        System.out.println("*************************************头像路径： "+newsUrl+"***************************************");
        return R.ok().put("url", newsUrl);
    }

    /**
     * 从阿里云下载文件 （以附件形式下载）
     */
    /*@ResponseBody
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    @IgnoreSign
    @IgnoreToken*/
    /*public void downLoadFile(HttpServletRequest request,HttpServletResponse response){
        try {
            //String fileid = request.getParameter("fileid").toString();//从前台获取当前下载文件的id值（每个上传到阿里云的文件都会有一个独一无二的id值）
            //String filename =request.getParameter("filename").toString();//从前台获取要下载文件的文件名
            //int i=filename.lastIndexOf("\\");
            //filename=filename.substring(i+1);
            String filename = "android_file/goodfa1.0.0.apk.1";

            // 读去Object内容  返回
            BufferedInputStream in=new BufferedInputStream( OSSUtil.getObject(Constants.IGM_BUCKET, "goodfa1.0.0.apk.1"));
            //System.out.println(ossObject.getObjectContent().toString());


            BufferedOutputStream out=new BufferedOutputStream(response.getOutputStream());
            //通知浏览器以附件形式下载
            response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(filename,"utf-8"));
            //BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(new File("f:\\a.txt")));

            byte[] car=new byte[1024];
            int L=0;
            while((L=in.read(car))!=-1){
                out.write(car, 0,L);

            }
            if(out!=null){
                out.flush();
                out.close();
            }
            if(in!=null){
                in.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    } */

	/**
	 * 二维码
	 */
    /*
	@RequestMapping("/QRcode")
	@ResponseBody
	public R QRcode(HttpServletRequest req) {

		Integer uid = ISsoLoginHelper.confirm(req);
		String url =  "";
		String content = url + "?invitationId = uid";

		WfMemberEntity memberEntity = memberService.queryObject(uid);
		String logoPath = "http://wangfang.oss-cn-qingdao.aliyuncs.com/" + memberEntity.getHeadimage();
		QRCodeUtil.encode(content, logoPath, output, true);
		//QRCodeUtil.encode(content, logoPath, output, true);

		return R.ok();
	}*/

    /**
     * 注册登录
     */
    @RequestMapping("/getToken")
    @IgnoreToken
    @ResponseBody
    public String getToken(Integer uid) {
        return ISsoLoginHelper.login(uid);
    }
	//自动生成名字
	public static String getRandomJianHan(int len) {
	    String ret = "";
	    for (int i = 0; i < len; i++) {
	        String str = null;
	        int hightPos, lowPos; // 定义高低位
	        Random random = new Random();
	        hightPos = (176 + Math.abs(random.nextInt(39))); // 获取高位值
	        lowPos = (161 + Math.abs(random.nextInt(93))); // 获取低位值
	        byte[] b = new byte[2];
	        b[0] = (new Integer(hightPos).byteValue());
	        b[1] = (new Integer(lowPos).byteValue());
	        try {
	            str = new String(b, "GBK"); // 转成中文
	        } catch (UnsupportedEncodingException ex) {
	            ex.printStackTrace();
	        }
	        ret += str;
	    }
	    return ret;
	}

	//生成随机数字和字母,
    public String getStringRandom(int length) {

        String val = "";
        Random random = new Random();

        //参数length，表示生成几位随机数
        for(int i = 0; i < length; i++) {

            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if( "char".equalsIgnoreCase(charOrNum) ) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char)(random.nextInt(26) + temp);
            } else if( "num".equalsIgnoreCase(charOrNum) ) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

	//生成随机数字和字母,
	public String getNikeName() {

		Random random = new Random();
		int r = random.nextInt(2);
		String[] arr = {"小猴","小宝"};
		return arr[r];
	}

	@IgnoreToken
	@ResponseBody
	@RequestMapping("gift")
	public R gift(@RequestBody MemberGift memberGift) {
		WfMemberEntity memberEntity = memberService.queryByMobile(memberGift.getTelephone());
		if (memberService.addGift(memberGift) == 0) {
			return R.ok().put("status", "3");
		}
		if (memberEntity != null) {
			List<MemberGift> list = memberService.searchGift(memberGift.getTelephone());
			if (list.size() > 0) {
				StringBuffer b = new StringBuffer();
				Integer userId = memberEntity.getUserid();
				String orderCode = DateUtil.getOrderNum();
				list.stream().forEach((item) -> {
					if (goodsOrderRelationService.confirm(new WfGoodsOrderRelationEntity(userId, item.getCourseId(), item.getCourseType()))) {
						b.append("b");
						memberService.updateGift(item.getId());
						goodsOrderRelationService.save(WfGoodsOrderRelationEntity.generateFreeEntity
								(userId, orderCode, item.getCourseId(), item.getCourseType()));
					}
				});
				if (StringUtils.isNotBlank(b.toString())) {
					goodsOrderService.save(WfGoodsOrderEntity.generateFreeEntity(memberEntity.getUserid(), orderCode));
				}
			}
		}
//			return R.ok().put("status", "2");  用户已注册
		return R.ok().put("status", "1");
	}

}
